package com.cowmooed.controller;

import com.cowmooed.dto.LoginDto;
import com.cowmooed.dto.RegisterDto;
import com.cowmooed.entity.Result;
import com.cowmooed.entity.SysUser;
import com.cowmooed.service.SysUserService;
import com.cowmooed.utils.AuthUtil;
import com.cowmooed.utils.BaseContextUtil;
import com.cowmooed.utils.MD5Util;
import io.swagger.annotations.Api;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 处理用户注册、登录等认证相关请求
 */
@Api(tags = "认证管理")
@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private AuthUtil authUtil;

    
    /**
     * 用户登录接口
     * @param loginDto 登录信息
     * @return 登录结果，包含accessToken和refreshToken
     */
    @ApiOperation(value = "用户登录", notes = "用户登录接口，返回双token和用户信息")
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto) {
        try {
            // 1. 对密码进行MD5加密
            String encryptedPassword = MD5Util.encrypt(loginDto.getPassword());
            
            // 2. 根据用户名和加密后的密码查询用户
            SysUser user = sysUserService.findByUserNameAndPassword(loginDto.getUserName(), encryptedPassword);
            if (user == null) {
                return Result.error("用户名或密码错误");
            }
            
            // 3. 生成双token
            String accessToken = authUtil.generateAccessToken(user.getUserName());
            String refreshToken = authUtil.generateRefreshToken(user.getUserName());
            
            // 4. 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("accessToken", accessToken);
            data.put("refreshToken", refreshToken);
            data.put("userName", user.getUserName());
            data.put("avatarUrl", user.getAvatarUrl());

            data.put("userId", String.valueOf(user.getUserId()));
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 刷新令牌接口
     * @return 新的accessToken和refreshToken
     */
    @ApiOperation(value = "刷新令牌", notes = "使用refreshToken获取新的accessToken和refreshToken")
    @GetMapping(value = "/refreshToken/{refreshToken}")
    public Result refreshToken(@PathVariable String refreshToken) {
        try {
            // 1. 验证refreshToken是否有效
            boolean isValid = authUtil.validateToken(refreshToken);
            if (!isValid) {
                return Result.error("无效的刷新令牌");
            }
            
            // 2. 从refreshToken中获取用户名
            String userName = authUtil.getUsernameFromToken(refreshToken);
            if (userName == null) {
                return Result.error("刷新令牌解析失败");
            }
            
            // 3. 查询用户信息，确保用户存在
            SysUser user = sysUserService.findByUserName(userName);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 4. 生成新的accessToken和refreshToken
            String newAccessToken = authUtil.generateAccessToken(userName);
            String newRefreshToken = authUtil.generateRefreshToken(userName);
            
            // 5. 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("accessToken", newAccessToken);
            data.put("refreshToken", newRefreshToken);
            
            return Result.success(data);
        } catch (ExpiredJwtException e) {
            return Result.error("刷新令牌已过期");
        } catch (Exception e) {
            return Result.error("刷新令牌失败: " + e.getMessage());
        }
    }
    
    /**
     * 用户注册接口
     * @param registerDto 注册信息
     * @return 注册结果
     */
    @ApiOperation(value = "用户注册", notes = "用户注册接口，支持上传头像")
    @PostMapping("/register")
    public Result register(RegisterDto registerDto) {
        try {
            boolean success = sysUserService.register(registerDto);
            if (success) {
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

}